package com.cskaoyan.javase.oop2._2polymorphic._2advantage.cast;
/**
 * 向下转换,强制类型转换的语法
 * 转换的是引用,父类引用 --> 子类引用
 * 语法:
 * 子类类名 引用名 = (子类类名)父类引用;
 *
 * 能够通过编译的前提:
 * 存在继承,必须把一个父类引用强转成它的子类,否者无法通过编译.
 *
 * 成功的前提:
 * 如果进行错误的向下转换,代码运行就会报错,抛出异常ClassCastException
 * 所以向下转型一旦失败,后果是很严重的
 *
 * 向下转型能够成功的前提是,强转后的引用,确实能够真的指向这个对象.
 * 具体来说:
 *      Grandfather gf = new Grandson();
 *      强转后的引用,要么就是之前父类引用指向的对象的类型(还原)
 *      Grandson gs = (Grandson) gf;
 *      强转后的引用,要么就是之前父类引用指向的对象的父类类型(这里仍然是父类引用指向子类对象)
 *      Father f = (Father) gf;
 *      Son s = (Son) gf;
 *
 * @since 15:02
 * @author wuguidong@cskaoyan.onaliyun.com
 */
public class Demo {
    public static void main(String[] args) {
        // 以下是能够通过编译的使用场景
        /*Grandfather gf = new Grandfather();
        Father f = (Father) gf;
        Son s = (Son) gf;
        Grandson gs = (Grandson) gf;*/
        // ((String) gf)

        Grandfather gf = new Grandson();
        Father f = (Father) gf;
        Son s = (Son) gf;
        Grandson gs = (Grandson) gf;
    }
}
class Grandfather { }
class Father extends Grandfather{}
class Son extends Father{}
class Grandson extends Son{}